<template>
  <div>
    <h2>药品管理</h2>
    <el-button type="primary" @click="openAdd()">新增药品</el-button>
    <el-table :data="tableData" row-key="medicineId">
      <el-table-column prop="medicineName" label="药品名称" />
      <el-table-column prop="specification" label="规格" />
      <el-table-column prop="quantity" label="库存" />

      <el-table-column label="有效期">
        <template #default="{ row }">
    <span :style="{ color: isExpiring(row.expiryDate) ? 'red' : '' }">
      {{ row.expiryDate }} {{ isExpiring(row.expiryDate) ? '（即将过期）' : '' }}
    </span>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" @click="del(row.medicineId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="show" title="新增药品">
      <el-form :model="form" label-width="100px">
        <el-form-item label="名称"><el-input v-model="form.medicineName" /></el-form-item>
        <el-form-item label="规格"><el-input v-model="form.specification" /></el-form-item>
        <el-form-item label="库存"><el-input-number v-model="form.quantity" /></el-form-item>
        <el-form-item label="有效期">
          <el-date-picker v-model="form.expiryDate" type="date" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getMedicineList, addMedicine, deleteMedicine } from '@/api/medicine'

const tableData = ref([])
const show = ref(false)
const form = ref({})

const load = async () => {
  const res = await getMedicineList()
  tableData.value = res.data || []   // ✅ 直接拿后端 data
}

const submit = async () => {
  await addMedicine(form.value)
  ElMessage.success('新增成功')
  show.value = false
  load()          // 立即刷新列表
}

const openAdd = () => {
  form.value = {}
  show.value = true
}


const del = async (id) => {
  await deleteMedicine(id)
  load()
}

const isExpiring = (date) => {
  const today = new Date()
  const expiry = new Date(date)
  const diff = (expiry - today) / (1000 * 60 * 60 * 24)
  return diff <= 30
}

onMounted(load)
</script>
